package beanstao.util.store.database.impl;

import java.util.Map.Entry;

import beanstao.util.Sber;
import beanstao.util.enums.DataType;
import beanstao.util.store.database.DbSetting;
import beanstao.util.store.database.Field;
import beanstao.util.store.database.Fields;


public class MysqlDbCreator extends AbstractDbCreator
{
	@Override
	public String checkTabel(String storeName)
	{
		String sql = "SHOW TABLES LIKE '" + storeName + "'";
		return sql;
	}

	@Override
	public String checkIndex(String storeName)
	{
		String sql = Sber.ME("SHOW INDEX FROM ").append(storeName).toString();
		return sql;
	}

	@Override
	public String checkFields(String storeName)
	{
		String sql = "DESC " + storeName;
		return sql;
	}

	@Override
	public String createTabel(String dbname, String storeName, Fields fields, DbSetting _DbSetting)
	{
		Sber sber = Sber.ME("CREATE TABLE ").append(storeName).append(" ( ");
		for (Entry<String, Field> entry : fields)
		{
			Field field = entry.getValue();
			if ("id".equals(field.getName()))
			{
				if (field.isPrimary())
				{
					if (field.isAutoIncrement())
						// 如果是ID字段，将该字段设为主键，自增长
						sber.append("id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,");
					else
						sber.append("id VARCHAR(64) PRIMARY KEY NOT NULL,");
				}
				else
					sber.append("id VARCHAR(64),");
				continue;
			}
			else if ("leak".equals(field.getName()))
			{
				sber.append("leak INT NOT NULL DEFAULT 1,");
				continue;
			}
			// 字段名
			sber.append(entry.getValue().getName()).append(" ");

			// 获取字段的数据类型
			DataType type = entry.getValue().getDataType();
			// 内存表 doesn't support BLOB/TEXT columns
			if ((type == DataType.TEXT) && _DbSetting.isMemTable())
				type = DataType.VARCHAR;

			// 添加字段的数据类型
			sber.append(type);
			if (!(type.equals(DataType.DATE)) && !(type.equals(DataType.DATETIME)))
				sber.append("(").append(entry.getValue().getLength()).append(") ");
			else
				sber.append(' ');
			sber.append(entry.getValue().getNullEnable() + ",");
		}
		sber.trimEnd();
		sber.append(")");
		if (_DbSetting.isMemTable())
			sber.append("ENGINE=MEMORY ");
		sber.append("DEFAULT CHARACTER SET = utf8 MAX_ROWS=10000 COLLATE = utf8_general_ci");

		return sber.toString();
	}

	@Override
	public String createIndex(String storeName, String column)
	{
		String sqlString = "ALTER TABLE " + storeName + " ADD INDEX " + column.toUpperCase() + "(" + column + ")";
		return sqlString;
	}

	@Override
	public String createFields(String storeName, Fields fields)
	{
		Sber sber = Sber.ME("ALTER TABLE ").append(storeName).append(" ADD ");
		for (Entry<String, Field> entry : fields)
		{
			sber.append(entry.getValue().getName() + ' ');
			sber.append(entry.getValue().getDataType());
			sber.append('(').append(entry.getValue().getLength()).append(')').append(' ');
			sber.append(entry.getValue().getNullEnable() + ",");
		}
		sber.trimEnd();
		sber.append(" )");
		return sber.toString();
	}
}
